package org.qhhc.hashmapandtable;

import java.util.HashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

public class HashMapTest {
    public static void main(String[] args) throws InterruptedException {
        // 创建线程不安全的HashMap实例（初始容量2，容易触发扩容）
        HashMap<Integer, String> unsafeMap = new HashMap<>(2, 0.75f);

        ExecutorService executor = Executors.newFixedThreadPool(10);

        // 创建10个并发线程执行put操作
        for (int i = 0; i < 10; i++) {
            final int threadId = i;
            executor.execute(() -> {
                for (int j = 0; j < 5000; j++) {
                    int key = threadId * 5000 + j;
                    unsafeMap.put(key, "Value-" + key);
                }
            });
        }

        executor.shutdown();
        executor.awaitTermination(1, TimeUnit.MINUTES);

        // 预期结果：50,000个条目（10线程*5000次put）
        System.out.println("最终HashMap大小：" + unsafeMap.size());
        // 实际结果可能小于50000（如48673、49521等）
    }
}